using System;
using System.Linq;
using NFreeMarker.Template;

namespace NFreeMarker.Ext.Beans
{
    /**
     * @author Attila Szegedi
     * @version $Id: EnumModels.java,v 1.1.2.3 2007/02/08 14:53:27 szegedia Exp $
     */
    class EnumModels : ClassBasedModelFactory
    {
        internal EnumModels(BeansWrapper wrapper)
            : base(wrapper)
        {
        }
        
        protected override ITemplateModel CreateModel(Type type)
        {
            Array obj = Enum.GetValues(type);
            if (obj == null)
            {
                // Return null - it'll manifest itself as undefined in the template.
                // We're doing this rather than throw an exception as this way 
                // people can use someEnumModel?default({}) to gracefully fall back 
                // to an empty hash if they want to.
                return null;
            }
            var map = obj
                .Cast<Enum>()
                .ToDictionary(value => Enum.GetName(value.GetType(), value));
            return new SimpleMapModel(map, GetWrapper());
        }
    }
}